import logging
import logging.config
import yaml
from pathlib import Path
import os

def setup_logging(
    default_path='src/config/logging.yaml',
    default_level=logging.INFO,
    env_key='LOG_CFG'
):
    """设置日志配置"""
    path = default_path
    value = os.getenv(env_key, None)
    if value:
        path = value
        
    if os.path.exists(path):
        with open(path, 'rt') as f:
            try:
                config = yaml.safe_load(f.read())
                # 确保日志目录存在
                log_dir = Path('logs')
                log_dir.mkdir(parents=True, exist_ok=True)
                
                logging.config.dictConfig(config)
            except Exception as e:
                print(f'Error in logging configuration: {e}')
                logging.basicConfig(level=default_level)
    else:
        logging.basicConfig(level=default_level)
        print(f'Unable to load logging config from {path}')

def get_logger(name):
    """获取logger实例"""
    return logging.getLogger(name)
